<?php

namespace app\nideshop\controller;

use app\nideshop\service\Weixin;
use app\nideshop\service\Token;
use think\Db;


class Collect extends Base
{
    protected $datas;


    public function listAction()
    {
        $this->datas = $this->params;
        $typeId = $this->datas['typeId'];
        $userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);

        $list = Db::name('collect')
        ->alias('c')
        ->join('goods g', 'c.value_id=g.id', 'left')
        ->field('c.*, g.name, g.list_pic_url, g.goods_brief, g.retail_price')
        ->where('user_id', $userId)
        ->where('type_id', $typeId)
        ->select();

        return json([
            'errno' => 0,
            'errmsg' => '成功',
            'data' => [
                'data' => $list
            ]
        ]);
    }

    public function addordeleteAction()
    {
        $this->datas = $this->params;
        $typeId = $this->datas['typeId'];
        $valueId = $this->datas['valueId'];
        $userId = Token::unlock_url($_SERVER['HTTP_X_NIDESHOP_TOKEN']);

        $collect = Db::name('collect')
        ->where('type_id', $typeId)
        ->where('value_id', $valueId)
        ->where('user_id', $userId)
        ->find();

        $collectRes = null;
        $handleType = 'add';

        if (empty($collect))
        {
            $collectRes = Db::name('collect')
            ->insert([
                'type_id' => $typeId,
                'value_id' => $valueId,
                'user_id' => $userId,
                'add_time' => time()
            ]);
        }
        else
        {
            // 取消收藏
            $collectRes = Db::name('collect')
            ->where('id', $collect['id'])
            ->delete();
            $handleType = 'delete';
        }
        if ($collectRes > 0)
        {
            return json([
                'errno' => 0,
                'errmsg' => '成功',
                'data' => [
                    'type' => $handleType
                ]
            ]);
        }

        return json([
            'errno' => 1,
            'errmsg' => '操作失败'
        ]);
    }
}
